package hr_project.hr.web.Emp;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import hr_project.hr.biz.Archives.IArchivesBiz;
import hr_project.hr.biz.Dept.IDeptBiz;
import hr_project.hr.biz.Emp.IEmpBiz;
import hr_project.hr.entity.Emp;
import hr_project.hr.util.QueryEmp;
import hr_project.hr.util.pagebean;
 
@Controller
@RequestMapping("/emp")
public class EmpAction {
	
	@Autowired
	private IEmpBiz biz;
	
	@Autowired
	private IArchivesBiz abiz;
	
	@Autowired
	private IDeptBiz dbiz;
	
	

	public IDeptBiz getDbiz() {
		return dbiz;
	}

	public void setDbiz(IDeptBiz dbiz) {
		this.dbiz = dbiz;
	}

	public IArchivesBiz getAbiz() {
		return abiz;
	}

	public void setAbiz(IArchivesBiz abiz) {
		this.abiz = abiz;
	}

	public IEmpBiz getBiz() {
		return biz;
	}

	public void setBiz(IEmpBiz biz) {
		this.biz = biz;
	}
	
	
	@RequestMapping("/log")
	@ResponseBody
	public ModelAndView login(String name,String pwd,String code,HttpSession sess,ModelAndView mv,String sta,HttpServletResponse res,HttpServletRequest req) throws IOException
	{
		
		Emp e=biz.getLog(name, pwd);

		String val_code=(String)sess.getAttribute("val_code");
		
		
		
		if(code.equalsIgnoreCase(val_code))
		{
			if(e==null)
			{
				mv.setViewName("login");
			}
			else
			{
				if(sta!=null && sta.equals("1"))
				{
					Cookie ck1=new Cookie("uname", e.getUs_name());
					ck1.setPath("/");
					ck1.setMaxAge(60*60*24*7);
					res.addCookie(ck1);
					Cookie ck2=new Cookie("pwd", e.getUs_password());
					ck2.setPath("/");
					ck2.setMaxAge(60*60*24*7);
					res.addCookie(ck2);
					 
					
				}
				sess.setAttribute("loger",e);
				mv.addObject("log", e);
				mv.setViewName("index");
			}
		}
		else
		{
			mv.setViewName("login");
		}
		return mv;
	}
	
	//自动登录
	@RequestMapping("/autolog")
	public void autolog(@CookieValue("uname")String name,@CookieValue("pwd")String pwd,HttpSession sess,HttpServletResponse res) throws IOException
	{
		System.out.println("---------------------------------------------"+name);
		Emp emp=biz.getLog(name, pwd);
		
		sess.setAttribute("loger", emp);
		res.getWriter().println("<script>parent.window.location.href='../index.jsp';</script>");
	}
	
	
	//list+query
	@RequestMapping("/querylist")
	@ResponseBody
	public pagebean list(QueryEmp query,@RequestParam(defaultValue="1")int page)
	{
		if(query==null) query=new QueryEmp();
		
		
		
		if(query.getProvince()!=null && !query.getProvince().equals(""))
		{
			String prov=query.getProvince();
			prov=prov.substring(prov.lastIndexOf("-")+1);
			query.setProvince(prov);
			
		}
		if(query.getCity()!=null && !query.getCity().equals(""))
		{
			String city=query.getCity();
			city=city.substring(city.lastIndexOf("-")+1);
			query.setCity(city);
		}
		
		
		pagebean pbean = biz.getAll(query, page);
		
		return pbean;
		
	}
	//列表其他部门
	@RequestMapping("/depother")
	@ResponseBody
	public List<Emp> list2(HttpSession sess)
	{
		
		Emp e=(Emp)sess.getAttribute("loger");
		
		System.out.println(e.getUs_depid());
		
		return biz.getOther(e.getUs_depid().getDe_id());
	}
	
	
	//列表本部门
	@RequestMapping("/deplist")
	@ResponseBody
	public pagebean list3(QueryEmp query,@RequestParam(defaultValue="1")int page,HttpSession sess)
	{
		if(query==null) query=new QueryEmp();
		
		Emp e=(Emp)sess.getAttribute("loger");
		
		
		System.out.println(e.getUs_depid());
		
		query.setDepid(e.getUs_depid().getDe_id());
		
		
		pagebean pbean = biz.getAll(query, page);
		
		return pbean;
		
	}
	
	//列表已删除员工
	@RequestMapping("/dellist")
	@ResponseBody
	public pagebean list3(QueryEmp query,@RequestParam(defaultValue="1")int page)
	{
		if(query==null) query=new QueryEmp();
		
		pagebean pbean = biz.getDel(query, page);
		
		return pbean;
		
	}
	
	//修改状态
	@RequestMapping("/mod2")
	public String modEmp2(String sta,long id)
	{
		Emp emp=biz.getById(id);
		
		emp.getA_id().setAr_status(sta);
		
		biz.modEmp(emp);
		
		return "emp/empdel_list";
	}
	
	//修改电话
	@RequestMapping("/mod4")
	public String modEmp4(String ph,long id)
	{
		Emp emp=biz.getById(id);
		
		System.out.println(ph);
		System.out.println(id);
		emp.setUs_phone(ph);
		
		biz.modEmp(emp);
		
		return "redirect:/emp/autolog.action";
	}
	
	//修改密码
	@RequestMapping("/mod3")
	public void modEmp3(String pwd,long id,HttpServletResponse res) throws IOException
	{
		Emp emp=biz.getById(id);
		
		emp.setUs_password(pwd);
		biz.modEmp(emp);
		
		res.getWriter().println("<script>parent.window.location.href='../login.jsp';</script>");
		
		
	}
	
	//修改信息
	@RequestMapping("/mod")
	public String modEmp(Emp e)
	{
		
		
		
		String prov=e.getA_id().getAr_province();
		String city=e.getA_id().getAr_city();
		String area=e.getA_id().getAr_district();
		
		
		prov=prov.substring(prov.lastIndexOf("-")+1);
		city=city.substring(city.lastIndexOf("-")+1);
		area=area.substring(area.lastIndexOf("-")+1);
		
		
		e.getA_id().setAr_province(prov);
		e.getA_id().setAr_city(city);
		e.getA_id().setAr_district(area);
		
		
		biz.modEmp(e);

		
			
	   return "emp/emp-list";
			 
		
	}
	
	
	//验证手机号
	@RequestMapping("/phones")
	@ResponseBody
	public void checkPhone(String key,HttpServletResponse res) throws IOException
	{
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setContentType("text/html;charset=utf-8");
		Emp e=biz.getByQuery(key);
		
		if(e==null)
		{
			res.getWriter().print("该手机号可以使用");
		}
		else
		{
			res.getWriter().print("手机号已经存在，请重新输入");
		}
	}
	
	
	//验证名字
	@RequestMapping("/names")
	@ResponseBody
	public void checkName(String key,HttpServletResponse res) throws IOException
	{
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setContentType("text/html;charset=utf-8");
		Emp e=biz.getByQuery(key);
		
		if(e==null)
		{
			res.getWriter().print("该名字可以使用");
		}
		else
		{
			res.getWriter().print("名字已经存在，请重新输入");
		}
	}
	
	@RequestMapping("/adds")
	@ResponseBody
	public void addEmp(Emp e,HttpSession sess,@RequestParam(value="img")MultipartFile eimg,HttpServletRequest req,HttpServletResponse res) throws IOException
	{
		System.out.println("iiiiiiiiiii                "+eimg);
		String prov=e.getA_id().getAr_province();
		String city=e.getA_id().getAr_city();
		String area=e.getA_id().getAr_district();
		
		
		prov=prov.substring(prov.lastIndexOf("-")+1);
		city=city.substring(city.lastIndexOf("-")+1);
		area=area.substring(area.lastIndexOf("-")+1);
		
		
		e.getA_id().setAr_province(prov);
		e.getA_id().setAr_city(city);
		e.getA_id().setAr_district(area);
		
		
		String path=req.getServletContext().getRealPath("images");
		
		String name=eimg.getOriginalFilename();
		
		FileUtils.copyInputStreamToFile(eimg.getInputStream(), new File(path+"/"+name));
	
		
		
		e.setAr_photo("images/"+name);
		Emp ee=(Emp)sess.getAttribute("loger");
		e.getA_id().setAr_regist(ee.getUs_id());
		biz.addEmp(e);
		res.getWriter().println("<script>location='emp-list.jsp';</script>");
	}
	
	
	@RequestMapping("/getbyid")
	public ModelAndView getById(ModelAndView mv,long id,int n)
	{ 
		Emp e=biz.getById(id);
		mv.addObject("emp",e);
		
		if(n==1)
		{
			mv.setViewName("emp/emp-show");
		}
		else if(n==2)
		{ 
			mv.setViewName("emp/emp-mod");
		}
		else if(n==3)
		{
			mv.setViewName("salary_add");
		}
		
		
		return mv;
	}
	
	
	//del
	@RequestMapping("/del")
	public String delEmp(long id)
	{
		Emp e=biz.getById(id);
		
		e.getA_id().setAr_status("已删除");
		
		biz.modEmp(e); 
		
		
		return "emp/emp-list";
	}
	
	//exit
	@RequestMapping("/exit")
	public String exit(HttpSession sess)
	{
		sess.invalidate();
		return "login";
	}
	
	
	//恢复已删除的员工
	@RequestMapping("/huifu")
	public String huiFu(long id)
	{
		Emp e=biz.getById(id);
		e.getA_id().setAr_status("正常");
		
		biz.modEmp(e);
		
		return "emp/empdel-list";
	}
	
	
	//制作饼图（统计部门薪资的情况）
	@RequestMapping("/piechart")
	@ResponseBody
	public List<Map<String, Object>> getCount()
	{
		return biz.getCountsum();
	}
	
	//制作柱状图（统计部门人数的情况）
	@ResponseBody
	@RequestMapping("/barchart")
	public Map<String, Object> getCount2()
	{
		List<Map<String, Object>> list=biz.getCount();
		List nn=new ArrayList();
		List vv=new ArrayList();
		for(Map<String, Object> mm:list)
		{
			nn.add(mm.get("name"));
			vv.add(mm.get("value"));
		}
		
		Map map=new HashMap<String, List>();
		map.put("names", nn);
		map.put("values", vv);
		
		return map;
	}
	
	
	//将员工信息导出到excel中
    @RequestMapping("/export")
    @ResponseBody
	public void export(HttpServletRequest request,HttpServletResponse response) throws Exception
	  {
	        response.reset(); //清除buffer缓存  
	        //Map<String,Object> map=new HashMap<String,Object>();  
	        // 指定下载的文件名  
	        response.setContentType("application/vnd.ms-excel;charset=UTF-8");  
	        response.setHeader("Content-Disposition","attachment;filename="+new String("员工信息表.xlsx".getBytes(),"iso-8859-1"));
	        //导出Excel对象  
	        XSSFWorkbook workbook = biz.emexcel();
	        OutputStream output;  
	        try {  
	            output = response.getOutputStream();  
	            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);  
	            bufferedOutput.flush();  
	            workbook.write(bufferedOutput);  
	            bufferedOutput.close();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }
	  }
    
    
    //获得所有员工
    @ResponseBody
    @RequestMapping("/getallxx")
    public List<Emp> getAll()
    {
    	return biz.getAllxx();
    }
	
	
	
	
	
	
	
	
	
}
